<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库单号" prop="receiptCode">
        <el-input v-model="queryParams.receiptCode" placeholder="请输入入库单编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待入库" value="PENDING" />
          <el-option label="已入库" value="RECEIVED" />
          <el-option label="已取消" value="CANCELLED" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['purchase:receipt:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['purchase:receipt:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['purchase:receipt:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-check" size="mini" :disabled="single" @click="handleAudit"
          v-hasPermi="['purchase:receipt:audit']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-s-promotion" size="mini" :disabled="single" @click="handleExecute"
          v-hasPermi="['purchase:receipt:execute']">执行</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['purchase:receipt:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单ID" align="center" prop="receiptId" />
      <el-table-column label="入库单编号" align="center" prop="receiptCode" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="入库日期" align="center" prop="receiptDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="总数量" align="center" prop="totalQuantity" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'PENDING'" type="warning">待入库</el-tag>
          <el-tag v-else-if="scope.row.status === 'RECEIVED'" type="success">已入库</el-tag>
          <el-tag v-else-if="scope.row.status === 'CANCELLED'" type="danger">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['purchase:receipt:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:receipt:edit']" v-if="scope.row.status === 'PENDING'">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-check" @click="handleAudit(scope.row)"
            v-hasPermi="['purchase:receipt:audit']" v-if="scope.row.status === 'PENDING'">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handleExecute(scope.row)"
            v-hasPermi="['purchase:receipt:execute']" v-if="scope.row.status === 'PENDING'">执行</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:receipt:remove']" v-if="scope.row.status === 'PENDING'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改采购入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单编号" prop="receiptCode">
              <el-input v-model="form.receiptCode" placeholder="请输入入库单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" clearable @change="handleSupplierChange"
                style="width: 100%">
                <el-option v-for="supplier in supplierList" :key="supplier.supplierId" :label="supplier.supplierName"
                  :value="supplier.supplierId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" clearable @change="handleWarehouseChange"
                style="width: 100%">
                <el-option v-for="warehouse in warehouseList" :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName" :value="warehouse.warehouseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="receiptDate">
              <el-date-picker clearable v-model="form.receiptDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择入库日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="receiptType">
              <el-select v-model="form.receiptType" placeholder="请选择入库类型" clearable style="width: 100%">
                <el-option label="正常入库" value="NORMAL" />
                <el-option label="退货入库" value="RETURN" />
                <el-option label="调拨入库" value="TRANSFER" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 入库明细 -->
        <el-divider content-position="left">入库明细</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetail">添加明细</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.receiptItemList" style="width: 100%">
          <el-table-column label="物料编码" prop="materialCode" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.materialId" placeholder="请选择物料" clearable
                @change="handleMaterialChange(scope.$index, scope.row)" style="width: 100%">
                <el-option v-for="material in materialList" :key="material.materialId" :label="material.materialCode"
                  :value="material.materialId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="materialName" width="150" />
          <el-table-column label="规格型号" prop="specification" width="120" />
          <el-table-column label="单位" prop="unit" width="80" />
          <el-table-column label="入库数量" prop="receiptQuantity" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" :precision="2" style="width: 100%"
                @change="calculateAmount(scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" style="width: 100%"
                @change="calculateAmount(scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.amount" :min="0" :precision="2" style="width: 100%" disabled />
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNumber" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchNumber" placeholder="请输入批次号" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete"
                @click="handleDeleteDetail(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReceipt, getReceipt, delReceipt, addReceipt, updateReceipt, checkReceiptCodeUnique, auditReceipt, executeReceipt } from "@/api/mes/purchase/receipt";
import { listMaterial } from "@/api/mes/basic/material";
import { listWarehouse } from "@/api/mes/inventory/warehouse";
import { listSupplier } from "@/api/mes/basic/supplier";

export default {
  name: "Receipt",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购入库单表格数据
      receiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptCode: null,
        supplierName: null,
        status: null
      },
      // 表单参数
      form: {
        receiptItemList: []
      },
      // 表单校验
      rules: {
        receiptCode: [
          { required: true, message: "入库单编号不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        receiptDate: [
          { required: true, message: "入库日期不能为空", trigger: "blur" }
        ],
        receiptType: [
          { required: true, message: "入库类型不能为空", trigger: "change" }
        ]
      },
      // 供应商列表 - 改为空数组
      supplierList: [],
      // 仓库列表
      warehouseList: [],
      // 物料列表
      materialList: []
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    this.getMaterialList();
    this.getSupplierList(); // 添加获取供应商数据
  },
  methods: {
    /** 查询采购入库单列表 */
    getList() {
      this.loading = true;
      listReceipt(this.queryParams).then(response => {
        this.receiptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取仓库列表 */
    getWarehouseList() {
      listWarehouse({}).then(response => {
        this.warehouseList = response.rows;
      });
    },
    /** 获取物料列表 */
    getMaterialList() {
      listMaterial({}).then(response => {
        this.materialList = response.rows;
      });
    },
    /** 获取供应商列表 */
    getSupplierList() {
      console.log('开始获取供应商数据...');
      listSupplier().then(response => {
        console.log('供应商数据加载成功:', response.rows);
        this.supplierList = response.rows;
      }).catch(error => {
        console.error('获取供应商列表失败:', error);
        this.$modal.msgError('获取供应商列表失败');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        receiptId: null,
        receiptCode: null,
        supplierId: null,
        warehouseId: null,
        receiptDate: null,
        receiptType: "NORMAL",
        status: "PENDING",
        remark: null,
        receiptItemList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.receiptId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购入库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const receiptId = row.receiptId || this.ids
      getReceipt(receiptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购入库单";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const receiptId = row.receiptId;
      getReceipt(receiptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看采购入库单";
        // 设置表单为只读
        this.$nextTick(() => {
          this.$refs.form.$el.querySelectorAll('input, select, textarea').forEach(el => {
            el.disabled = true;
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 计算总金额和总数量
          this.calculateTotals();

          if (this.form.receiptId != null) {
            updateReceipt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReceipt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const receiptIds = row.receiptId || this.ids;
      this.$modal.confirm('是否确认删除采购入库单编号为"' + receiptIds + '"的数据项？').then(function () {
        return delReceipt(receiptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      const receiptId = row.receiptId || this.ids[0];
      this.$modal.confirm('是否确认审核该入库单？').then(function () {
        return auditReceipt(receiptId, "RECEIVED");
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => { });
    },
    /** 执行按钮操作 */
    handleExecute(row) {
      const receiptId = row.receiptId || this.ids[0];
      this.$modal.confirm('是否确认执行该入库单？').then(function () {
        return executeReceipt(receiptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("执行成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/receipt/export', {
        ...this.queryParams
      }, `receipt_${new Date().getTime()}.xlsx`)
    },
    /** 供应商变化处理 */
    handleSupplierChange(value) {
      const supplier = this.supplierList.find(item => item.supplierId === value);
      if (supplier) {
        this.form.supplierCode = supplier.supplierCode;
        this.form.supplierName = supplier.supplierName;
      }
    },
    /** 仓库变化处理 */
    handleWarehouseChange(value) {
      const warehouse = this.warehouseList.find(item => item.warehouseId === value);
      if (warehouse) {
        this.form.warehouseCode = warehouse.warehouseCode;
        this.form.warehouseName = warehouse.warehouseName;
      }
    },
    /** 添加明细 */
    handleAddDetail() {
      this.form.receiptItemList.push({
        materialId: null,
        materialCode: null,
        materialName: null,
        specification: null,
        unit: null,
        quantity: 0,  // 改为 quantity
        unitPrice: 0,
        amount: 0,
        batchNumber: null,
        remark: null
      });
    },
    /** 删除明细 */
    handleDeleteDetail(index) {
      this.form.receiptItemList.splice(index, 1);
      this.calculateTotals();
    },
    /** 物料变化处理 */
    handleMaterialChange(index, row) {
      const material = this.materialList.find(item => item.materialId === row.materialId);
      if (material) {
        this.form.receiptItemList[index].materialCode = material.materialCode;
        this.form.receiptItemList[index].materialName = material.materialName;
        this.form.receiptItemList[index].specification = material.specification;
        this.form.receiptItemList[index].unit = material.unit;
      }
    },
    /** 计算金额 */
    calculateAmount(index) {
      const item = this.form.receiptItemList[index];
      item.amount = (item.quantity || 0) * (item.unitPrice || 0);  // 改为 quantity
      this.calculateTotals();
    },
    /** 计算总计 */
    calculateTotals() {
      let totalQuantity = 0;
      let totalAmount = 0;
      this.form.receiptItemList.forEach(item => {
        totalQuantity += item.quantity || 0;  // 改为 quantity
        totalAmount += item.amount || 0;
      });
      this.form.totalQuantity = totalQuantity;
      this.form.totalAmount = totalAmount;
    }
  }
};
</script>